<template>
    <view class="andry-goods-detail">
        <StatusBar v-show="isStatusBar" />
        <view v-if="bannerList.length>0" >
            <Banner id="goods" :banner-list="bannerList" />
        </view>
        <view class="cell productinfo">
            <view class="flex items-center justify-between">
                <view class="money">
                    <span class="unit">￥</span>
                    <span class="price">{{ productdetails.price }}</span>
                </view>
                <view>总库存{{ productdetails.stockStatusName }}</view>
            </view>
            <view class="title">
                <span class="sub-title">{{ productdetails.name }}</span>
            </view>
            <view class="title">
                <span class="sub-title">{{ productdetails.code }}</span>
            </view>
            <view class="tag">{{ productdetails.description }}</view>
            <view class="jifen">
                <span class="tags">可用{{ productdetails.point }}积分换购</span>
            </view>
        </view>
        <view class="cell productinfo">
            <view class="cell-option" @click="onCartShow">
                <view class="checked">
                    <view class="detail">
                        <span class="option-title">选择</span>
                        <span class="txt text-ellipsis">{{currentspec?currentspec:'请选择规格'}}</span>
                    </view>
                    <view>
                        <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
                    </view>
                </view>
            </view>
            <view class="cell-option">
                <view class="address" @click="gotoAddress">
                    <view class="detail">
                        <span class="option-title">送至</span>
                        <up-icon name="map" size="14" color="rgba(214, 142, 68, 1)" :bold="true" />
                        <span class="txt">{{address.provinceCityArea }}</span>
                    </view>
                    <view>
                        <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
                    </view>
                </view>
            </view>
        </view>
        <view class="detail-cell" style="padding-bottom: 150rpx;">
            <u-tabs :list="chartTabs" :current="currentChartTab" @change="onChartTabChange" lineColor="#c4996c"
                itemStyle="flex:1; height: 48px;" :activeStyle="{
                    color: '#c4996c',
                    fontWeight: 'bold'
                }" :inactiveStyle="{
                    color: '#333',
                    fontSize: '28rpx'
                }"></u-tabs>
            <view v-if="currentChartTab == 0">
                <mp-html :content="introduceList"></mp-html>
            </view>
            <view v-if="currentChartTab == 1">
                <view class="inventory-table">
                    <view class="inventory-headers">
                        <view >店铺：{{ shopName }}</view>
                        <view v-if="productdetails.shopTotalInventory">库存:{{ productdetails.shopTotalInventory }}</view>
                    </view>
                    <view v-if="showType == 1">
                        <view v-for="(item,index) in specifList" :key="index" class="inventory-row">
                            <view class="specname">
                                <view class="name">{{ item.name }}</view>
                            </view>
                            <view>
                                <view v-for="(spec, specIndex) in item.sizelist" :key="specIndex" class="speccontent">
                                    <view class="spec-name">{{ spec.sizevalue.value }}</view>
                                    <view class="spec-quantity">库存x{{ getInventoryBySkuCode(spec.originalSku.skuCode) }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view v-if="showType == 2">
                        <view v-for="(colorData, color) in groupedData" :key="color">
                            <view style="border-radius:10rpx;margin-bottom:20rpx;padding:6rpx 16rpx;background: rgba(243, 243, 243, 1);font-size:24rpx;display: inline-block;">{{color}}</view>
                            <up-scroll-list>
                                <view class="table">
                                    <view class="table-header header-cell">
                                        <view class="cell color-cell">
                                            <u-text text="尺码" size="14" color="#666666"></u-text></view>
                                        <view v-for="size in bandSizes" :key="size" class="cell1">
                                            <u-text :text="size" size="14" color="#666666"></u-text>
                                        </view>
                                    </view>
                                    <view v-for="(cupSize, index) in cupSizes" :key="index" class="table-row">
                                        <view class="cell color-cell">
                                            <u-text :text="cupSize" size="14" center="center" color="#666666"></u-text>
                                        </view>
                                        <view v-for="(bandSize, sizeIndex) in bandSizes" :key="sizeIndex" class="cell color-cell">                                   
                                            <u-text :text="colorData[cupSize] && colorData[cupSize][bandSize]? colorData[cupSize][bandSize]: 0" size="14" center="center" color="#666666"></u-text>
                                        </view>
                                    </view>
                                </view>
                            </up-scroll-list>
                        </view>
                    </view>

                </view>
            </view>
        </view>
        <view class="bottom">
            <view class="bottom-option" @click="openConversationList">
                <view class="item">
                    <img :src="IMG_URL2+'mine/service.svg'" />
                    <span>客服</span>
                </view>
            </view>
            <view class="bottom-option" @click="onCollect">
                <view class="item">
                    <img :src="isCollect ? IMG_URL2+'mine/star-filled.svg' : IMG_URL2+'mine/star.svg'" />
                    <span>收藏</span>
                </view>
            </view>
            <view class="bottom-option" @click="onCartPage(1)">
                <view class="item">
                    <div class="bade">
                        <up-badge :type="cunttype" :value="cuntvalue" bgColor="#f00"></up-badge>
                    </div>
                    <img :src="IMG_URL2+'mine/cart.svg'" />
                    <span>购物车</span>
                </view>
            </view>
            <view class="button">
                <view class="left" @click="onCartPage(2)">
                    加入购物车
                </view>
            </view>
        </view>
        <view v-if="showType==1">
            <Check v-if="shopCheckShow" :specif-list="specifList" :chooseProject="chooseProject" :spec-type="specType" @close="shopCheckShow = false"
            @cart="onCartGoods" @pay="onPayGoods" />
        </view>
        <view v-if="showType==2">
            <Check1
                v-if="shopCheckShow"
                :specif-list="specifList"
                :spec-type="specType"
                @close="shopCheckShow = false"
                @cart="onCartGoods1"
                @pay="onPayGoods1"
            />
        </view>
        <BackTop :backTop="backTop" />
    </view>
</template>

<script setup>
import { IMG_URL2 } from "@/config";
import StatusBar from "@/components/status-bar.vue";
import Banner from "./components/banner.vue";
import Check from "./components/check.vue";
import Check1 from "./components/check1.vue";
import BackTop from "@/components/back-top.vue";
import _superantUtils from "@/utils/util";
import { getStorage } from "@/utils/storage";
import { shopApi } from "@/api";

const inventoryData = ref([])

let currentspec=ref('')
const isStatusBar = ref(false);
const bannerList = ref([]);
let bannerList1 =ref([])
const currentChartTab = ref(0)
const shopName = ref(getStorage('shopName'))
let showType = ref(1)
// 地址id
const address = ref({
    id: "",
    provinceCityArea: "",
});
let shopReceiveId = ref(null)
const chartTabs = [
    { name: '图文详情' },
    { name: '店铺库存' }
]
const cunttype = ref('warning');
const cuntvalue = ref(100);
// 存储购物车数据
const cartData = ref([]);
const totalInventory = ref('');

// Group data by color, then by cup size and band size
const groupedData = computed(() => {
  const result = {};

  inventoryData.value.forEach(item => {
    const color = item.attributeList.find(attr => attr.name === "颜色").value;
    const cupSize = item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 2).value;
    const bandSize = item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 3).value;
    
    // 获取匹配的库存
    let inventory = 0;
    if (productdetails.shopSkuList && Array.isArray(productdetails.shopSkuList)) {
      const matchedSku = productdetails.shopSkuList.find(sku => sku.skuCode === item.skuCode);
      inventory = matchedSku ? matchedSku.inventory : 0;
    }

    if (!result[color]) {
      result[color] = {};
    }
    if (!result[color][cupSize]) {
      result[color][cupSize] = {};
    }
    result[color][cupSize][bandSize] = inventory;
  });

  return result;
});

const getInventoryBySkuCode = (skuCode) => {
    if (!productdetails.shopSkuList || !Array.isArray(productdetails.shopSkuList)) {
        return 0;
    }
    
    const matchedSku = productdetails.shopSkuList.find(sku => sku.skuCode === skuCode);
    return matchedSku ? matchedSku.inventory : 0;
};

const cupSizes = computed(() => {
  return [...new Set(inventoryData.value.map(item => 
    item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 2).value
  ))].sort();
});

const bandSizes = computed(() => {
  return [...new Set(inventoryData.value.map(item => 
    item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 3).value
  ))].sort((a, b) => a - b); // Sort numerically
});

let productId = ref(null)
let addcartList = ref(null)

let productdetails = reactive({
    price: '',
    name: '',
    point: 0,
    description:'',
    stockStatusName: '',
    receiveProvince: '', //省
    receiveCity: '',// 市
    receiveStreet: '', // 区
    receiveAddress: '',// 地址
    totalStock:'',
    shopTotalInventory:'',
    shopSkuList:[]
})

const current = ref(0);
const introduceList = ref('');
const isCollect = ref(true);
// 规格
const specifList = ref([]);
const chooseProject =ref([])
const shopCheckShow = ref(false);
const specType = ref(1);

// 返回顶部
const backTop = ref(0);
const onChartTabChange = (item) => {
    currentChartTab.value = item.index

}
// 获取购物车数
const getpurchaseCartcount = () => {
	shopApi.PURCHASECARTCOUNT().then((res) => {
		if (res.code == 200) {
            cuntvalue.value = res.result
		}else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

	})

};
const getDataDetail = (Id) => {
    shopApi.CATEGORYGETFRONTPRODUCTDETAILBYID({ id: Id }).then((res) => {
        if (res.code == 200) {
            introduceList.value = matchRichHtml(res.result.picDetail)
            bannerList1.value = res.result.images
            bannerList.value = res.result.images?res.result.images.split(','):''
            productdetails.price = res.result.price
            productdetails.name = res.result.name
            productdetails.point = res.result.point

            productdetails.description = res.result.description
            productdetails.stockStatusName = res.result.stockStatusName

            productdetails.receiveProvince = res.result.receiveProvince //省
            productdetails.receiveCity = res.result.receiveCity // 市
            productdetails.receiveStreet = res.result.receiveStreet // 区
            productdetails.receiveAddress = res.result.receiveAddress // 地址

            productdetails.code = res.result.code


            productdetails.totalStock = res.result.totalStock
            productdetails.shopTotalInventory = res.result.shopTotalInventory
            productdetails.shopSkuList = res.result.shopSkuList
            

            isCollect.value = res.result.collect

            let newdata = res.result.skuList;
            totalInventory.value = newdata.reduce((acc, sku) => acc + sku.inventory, 0);



            for (let i = 0; i < newdata.length; i++) {
                newdata[i].newattributeList=resetArray(newdata[i].attributeList)
                newdata[i].price = res.result.price
            }
            if (newdata.length > 0 && Array.isArray(newdata[0].newattributeList) && newdata[0].newattributeList.length >= 3) {
                showType.value = 2;
                inventoryData.value = newdata
                specifList.value =newdata

                getCartData(1);
                console.log(specifList.value,'-------specifList.value-----');
            }else{
                const groupedMap = new Map();
                // console.log(newdata,'newdata');
                newdata.forEach((sku) => {
                    // 提取颜色、尺寸和库存
                    const color = sku.newattributeList.find((attr) => attr.name === "颜色").value;
                    const colorvalue=sku.newattributeList.find((attr) => attr.name === "颜色")
                    const sizeValue = sku.newattributeList.find((attr) => attr.name === "尺寸")
                    const size = sku.newattributeList.find((attr) => attr.name === "尺寸").value;
                    const inventory = sku.inventory;

                    // 判断库存状态
                    let status = "无货";
                    if (inventory > 3) status = "库存充足";
                    else if (inventory > 0) status = "库存紧张";

                    let num = 0

                    // 构建当前 SKU 数据
                    const sizeData = { size,sizevalue:sizeValue,colorvalue:colorvalue, inventory, status,num,originalSku: sku };

                    // 将数据按颜色分组
                    if (!groupedMap.has(color)) {
                    groupedMap.set(color, []); // 初始化分组
                    }
                    groupedMap.get(color).push(sizeData);
                });
                

                // 2. 转换为目标数组格式
                const newresult = [];
                let price = res.result.price
                groupedMap.forEach((sizelist, name) => {
                    // 对sizelist按size从小到大排序
                    const sortedSizelist = sizelist.sort((a, b) => {
                        // 将size转换为数字进行比较
                        const sizeA = parseFloat(a.size) || 0;
                        const sizeB = parseFloat(b.size) || 0;
                        return sizeA - sizeB;
                    });
                    
                    newresult.push({ name, price, sizelist: sortedSizelist, checked: false });
                });
                specifList.value = newresult
                console.log(newresult,'newresult');
                getCartData(2)
            }





        } else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

    })
}

// 获取购物车数据并回显
const getCartData = (type) => {
  let params = {
    currentPage: 1,
    pageSize: 99999,
    productId: productId.value,
  };
  shopApi.PURCHASECARTLIST(params).then((res) => {
    if (res.code == 200) {
      const cartData = res.result.data[0].skuList || [];
      console.log("cartData:", cartData);
      // 回显购物车数据
      if(type===1){

        let newcartData = [];
        for (let i = 0; i < cartData.length; i++) {
            const item = cartData[i];
            console.log(item,'item');
            newcartData.push({
                purchaseCartId: res.result.data[0].purchaseCartId,
                productId: res.result.data[0].productId,
                productCode: res.result.data[0].productCode,
                name: res.result.data[0].name,
                productImg: res.result.data[0].productImg,
                unitPrice: res.result.data[0].unitPrice,
                productSkuId: item.productSkuId,
                productSkuCode: item.productSkuCode,
                skuSpec: item.skuSpec,
                skuImg: item.skuImg,
                quantity: item.quantity,
                stock: item.stock
            });
        }
        
        // 同步购物车数量到规格列表
        if (specifList.value && Array.isArray(specifList.value)) {
            specifList.value.forEach(item => {
                // 获取当前规格的颜色和尺码值
                const colorAttr = item.newattributeList.find(attr => attr.name === "颜色");
                const size1Attr = item.newattributeList.find(attr => attr.name === "尺寸" && attr.sort === 2);
                const size2Attr = item.newattributeList.find(attr => attr.name === "尺寸" && attr.sort === 3);
                
                if (colorAttr && size1Attr && size2Attr) {
                    // 构建规格字符串，与购物车的skuSpec格式相同
                    const specString = `${colorAttr.value};${size1Attr.value};${size2Attr.value}`;
                    
                    // 查找匹配的购物车项
                    const matchedCartItem = newcartData.find(cartItem => cartItem.skuSpec === specString);
                    
                    // 如果找到匹配项，设置数量
                    if (matchedCartItem) {
                        item.quantity = matchedCartItem.quantity;
                    }
                }
            });
        }

        console.log(newcartData,'newcartData',specifList.value);
        applyCartData1(res.result.data); // 更新 currentspec 和其他状态


      }else{
        applyCartData2(cartData);
      }
      
    }
  }).catch((err) => {
    // console.error('获取购物车数据失败:', err);
  });
};

const convertCartToSpecifList = (cartData) => {
  const specifList = [];
  if (!cartData || !cartData[0] || !cartData[0].skuList) {
    console.warn("cartData 为空或无 skuList");
    return specifList;
  }

  const product = cartData[0];
  const { unitPrice, productImg } = product;

  product.skuList.forEach(sku => {
    const { productSkuId, productSkuCode, skuSpec, stock, quantity, skuImg } = sku;
    const specParts = skuSpec.split(';');
    if (specParts.length < 3) {
      console.warn(`无效的 skuSpec: ${skuSpec}`);
      return;
    }
    const color = specParts[0];
    const cupSize = specParts[1];
    const bandSize = specParts[2];

    specifList.push({
      name: color,
      price: unitPrice,
      stock: stock,
      inventory: stock,
      skuPic: skuImg || (productImg ? productImg.split(',')[0] : ''),
      skuCode: productSkuCode,
      productSkuId: productSkuId,
      attributeList: [
        { name: "颜色", sort: 1, value: color, productSkuId: productSkuId },
        { name: "尺寸", sort: 2, value: cupSize },
        { name: "尺寸", sort: 3, value: bandSize }
      ],
      cupSize: cupSize,
      bandSize: bandSize
    });
  });
  

  return specifList;
};



// 将购物车数据应用到 sizeSelections（showType == 2）
const applyCartData1 = (cartData) => {
  let selectedSpecs = [];

  if (!cartData || !cartData[0] || !cartData[0].skuList) {
    currentspec.value = '请选择规格';
    console.log('cartData 为空，currentspec 设置为默认值');
    return;
  }

  const skuList = cartData[0].skuList;
  skuList.forEach((sku) => {
    const specParts = sku.skuSpec.split(';');
    if (specParts.length < 3) {
      console.warn(`无效的 skuSpec: ${sku.skuSpec}`);
      return;
    }

    const color = specParts[0];
    const cupSize = specParts[1];
    const bandSize = specParts[2];

    if (sku.quantity > 0) {
      selectedSpecs.push(`${color};${cupSize};${bandSize} × ${sku.quantity}`);
    }
  });

  currentspec.value = selectedSpecs.join('、') || '请选择规格';
  console.log('currentspec:', currentspec.value);
};
// 将购物车数据应用到 specifList
const applyCartData2 = (skuList) => {
  // 重置所有颜色和尺码的选择
  specifList.value.forEach((colorItem, colorIndex) => {
    colorItem.checked = false; // 重置选中状态
    colorItem.sizelist.forEach((sizeItem) => {
      sizeItem.num = 0; // 重置数量
    });
  });

  console.log("skuList:", specifList.value);

  let hasSelection = false;
  skuList.forEach((sku) => {
    const [color, size] = sku.skuSpec.split(';'); // 解析 skuSpec，如 "凝灰露;70"
    const colorIndex = specifList.value.findIndex(item => item.name === color);
    if (colorIndex !== -1) {
      const sizeIndex = specifList.value[colorIndex].sizelist.findIndex(item => item.size === size);
      if (sizeIndex !== -1) {
        specifList.value[colorIndex].sizelist[sizeIndex].num = sku.quantity; // 设置数量
        if (!hasSelection) {
          // 默认选中第一个有数量的颜色
          current.value = colorIndex;
          specifList.value[colorIndex].checked = true;
          hasSelection = true;
        }
      }
    }
  });

  // 如果没有购物车数据，保持默认状态（第一个颜色选中，所有 num 为 0）
  if (!hasSelection && specifList.value.length) {
    specifList.value[0].checked = true;
    current.value = 0;
  }

  let selectedSpecs = [];
    specifList.value.forEach(item => {
        item.sizelist.forEach(element => {
            if(element.num > 0) {
                console.log(element,'element');
                selectedSpecs.push(formatSelectedSpec1(element.colorvalue.value, element.sizevalue.value,element.num));
            }
        });
    });
    console.log(selectedSpecs,'selectedSpecs');
    currentspec.value = selectedSpecs.join('、');
};

const resetArray = (inputArray)=>{
    inputArray.forEach(element => {
        element.num=1
    });
    return Object.values(inputArray.reduce((acc, current) => {
            const key = `${current.name}-${current.sort}`;
            acc[key] = current;
            return acc;
        }, {}));

}
// 获取默认收货地址
const getAddressDefault = () => {
    shopApi.SHOPRECEIVEGGETDEFAULTADDRESS().then((res) => {
        if (res.code == 200) {
            const data = res.result;
            address.value = {
                shopReceiveId: data.shopReceiveId,
                provinceCityArea: data.province + data.city + data.street + data.detailAddress,
            };
            shopReceiveId.value = data.shopReceiveId
        }else{
            uni.showToast({
                title: res.errMsg,
                icon: "error",
            });
        }
    });
};
onLoad((option) => {
    // 初始化小程序和APP状态栏的颜色
    uni.setNavigationBarColor({
        frontColor: "#000000",
        backgroundColor: "#ffffff"
    });
    if (option.id) {
        productId.value = option.id
        getDataDetail(option.id)
    }
    getpurchaseCartcount()
    getAddressDefault()
});

onShow(() => {
    // getAddressDefault()
    uni.$on("check-address", (data) => {
        address.value = {
            shopName: data.shopName,
            city: data.city,
            cityCode: data.cityCode,
            detailAddress: data.detailAddress,
            isDefault: data.isDefault,
            name: data.name,
            phone: data.phone,
            province: data.province,
            provinceCode: data.provinceCode,
            shopId: data.shopId,
            shopName: data.shopName,
            shopReceiveId: data.shopReceiveId,
            street: data.street,
            streetCode: data.streetCode,
            provinceCityArea: data.province + data.city + data.street + data.detailAddress,
        };
        shopReceiveId.value = data.shopReceiveId
    });
});



onMounted(() => {
    
});

// 监听页面滚动(一键置顶，tabs吸顶)
onPageScroll((e) => {
    backTop.value = e.scrollTop;
});


// 加入购物车-显示规格列表
const onCartShow = () => {
    specType.value = 1;
    shopCheckShow.value = true;
    console.log(showType.value,'showType')
};
// 去收货地址列表
const gotoAddress = () => {
    uni.navigateTo({
        url: `/pages/user/address/index?type=goods&shopReceiveId=${shopReceiveId.value}`
    });
}


// 打开会话列表
const openConversationList = () => {
    uni.navigateTo({ url: '/pages/user/customerservice' });
};

// 跳到购物车
const onCartPage = (type) => {
    if(type == 1) {
        uni.switchTab({
            url: "/pages/index/cart"
        });
    }else{
        if (!currentspec.value|| !addcartList.value) {
            specType.value = 1;
            shopCheckShow.value = true;
            return;
        }
        console.log(addcartList.value,'addcartList')

        addCart(addcartList.value)


    }
};



// 加入购物车
const onCartGoods = (itemlist) => {

    shopCheckShow.value = false;

    let selectedSpecs = [];
    itemlist.forEach(item => {
        item.sizelist.forEach(element => {
            if(element.num > 0) {
                selectedSpecs.push(formatSelectedSpec1(element.colorvalue.value, element.sizevalue.value,element.num));
            }
        });
    });
    currentspec.value = selectedSpecs.join('、');

    uni.showToast({
        title: "已选择商品规格",
        icon: "success",
        mask: true
    });
    console.log(selectedSpecs,'selectedSpecs')
    addCart(itemlist);
}

const formatSelectedSpec1 = (colorValue, sizeValue,quantity) => {
  return `${colorValue};${sizeValue} × ${quantity}`;
};

const onCartGoods1 = (item) => {

    shopCheckShow.value = false;

    let selectedSpecs = [];
    console.log(item,'item')
    item.forEach(element => {
        if(element.quantity > 0) {
            selectedSpecs.push(`${element.color};${element.cupSize};${element.bandSize} × ${element.quantity}`);
        }
    });
   
    currentspec.value = selectedSpecs.join('、');

    uni.showToast({
        title: "已选择商品规格",
        icon: "success",
        mask: true
    });

    let newproducts = [];
    let params = {
        name: productdetails.name,
        productId: productId.value,
        productImg: bannerList1.value,
        productSkuId: item.productSkuId, // Assuming you want the first item's SKU ID
        products: item.map((nitem) => ({
            name: productdetails.name,
            productId: productId.value,
            productImg: bannerList1.value,
            productSkuId: nitem.productSkuId,
            quantity: nitem.quantity,
            skuImg: nitem.skuPic,
            skuSpec: `${nitem.color};${nitem.cupSize};${nitem.bandSize}`,
            unitPrice: productdetails.price,
            productSkuCode: nitem.skuCode,
            productCode: productdetails.code,
        }))
    };
    console.log(params,'params')


    shopApi.PURCHASECARTSAVEORUPDATEBATCH(params).then((res) => {
        if (res.code == 200) {
            uni.showToast({
                title: "已加入到购物车",
                icon: "success",
                mask: true
            });
            getDataDetail(productId.value)
            getpurchaseCartcount()
            // setTimeout(() => {
            //     uni.switchTab({
            //         url: "/pages/index/cart"
            //     });
            // }, 2000);
            
        } else {
            uni.showToast({
                title: res.errMsg,
                icon: "none",
                duration: 1000
            });
        }
    });

};
const addCart = (itemlist) => {
    console.log(itemlist, 'itemlist');
    let newproducts = [];
    itemlist.forEach(item => {
        if(item.sizelist.length > 0) {
            item.sizelist.forEach(element => {
                if(element.num > 0) {
                    newproducts.push({
                        name: productdetails.name,
                        productId: productId.value,
                        productImg: bannerList1.value,
                        productSkuId: element.sizevalue.productSkuId,
                        quantity: element.num,
                        skuImg: element.originalSku.skuPic,
                        skuSpec: `${element.colorvalue.value};${element.sizevalue.value}`,
                        unitPrice: productdetails.price,
                        productSkuCode: element.originalSku.skuCode,
                        productCode: productdetails.code,
                    });
                }
            });
        }
    });

    let params = {
        name: productdetails.name,
        productId: productId.value,
        productImg: bannerList1.value,
        productSkuId: itemlist[0].productSkuId, // Assuming you want the first item's SKU ID
        products: newproducts
    };

    shopApi.PURCHASECARTSAVEORUPDATEBATCH(params).then((res) => {
        if (res.code == 200) {
            uni.showToast({
                title: "已加入到购物车",
                icon: "success",
                mask: true
            });
            getpurchaseCartcount()

            getDataDetail(productId.value)
            // setTimeout(() => {
            //     uni.switchTab({
            //         url: "/pages/index/cart"
            //     });
            // }, 2000);
        } else {
            uni.showToast({
                title: res.errMsg,
                icon: "none",
                duration: 1000
            });
        }
    });
};
const onPayGoods = (spec) => {
    shopCheckShow.value = false;
    uni.navigateTo({
        url: "/pagesA/order/confirm?spec=" + JSON.stringify(spec) + "&type=goods"
    });
};

const onPayGoods1 = (item) => {
    shopCheckShow.value = false;
    uni.navigateTo({
        url: "/pagesA/order/confirm?spec=" + JSON.stringify(item) + "&type=goods"
    });
}

// 收藏/取消收藏
const onCollect = () => {
    isCollect.value = !isCollect.value;
    AddOrCancel()
};

// 取消或收藏商品
const AddOrCancel = () => {
    let data = {
        collect: isCollect.value,
        productId: productId.value
    }
    shopApi.COLLECTADDCOLLECT(data).then((res) => {

        if (res.code == 200) {
            uni.showToast({
                title: isCollect.value?'收藏成功':'已取消收藏',
                icon: "none",
                duration: 1000
            });

        } else {
            uni.showToast({
                title: '取消收藏',
                icon: "none",
                duration: 1000
            });
        }

    })
}


// 富文本内容格式化
const matchRichHtml = (data) => {
    if (!data) return '';

    // 如果 data 是对象且有 data 属性
    const content = typeof data === 'object' ? data.data : data;

    // 确保 content 是字符串
    if (typeof content !== 'string') return '';

    return content.replace(/< img/g, '<img');
};
</script>

<style lang="scss">
// APP窗口背景色默认白色，需用此种方式调整窗口背景色
page {
    background-color: #ededed;
}
</style>
<style lang="scss" scoped>
.andry-goods-detail {
    .header {
        position: fixed;
        top: 0;
        /* #ifdef APP-PLUS */
        top: var(--status-bar-height);
        /* #endif */
        z-index: 999;
        width: 100%;
        height: 44px;
        padding: 0rpx 12rpx 0rpx 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;

        .left-option,
        .right-option {
            display: flex;
            align-items: center;

            .left-image {
                margin-right: 12rpx;
                width: 44rpx;
                height: 44rpx;
                padding: 8rpx;
                box-sizing: border-box;
            }

            .right-image {
                margin-right: 12rpx;
                padding: 8rpx;
                box-sizing: border-box;
            }

            image {
                width: 44rpx;
                height: 44rpx;
            }
        }

        .resetImage {
            display: flex;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
        }
    }
    .productinfo{
        background: #fff;
        padding: 24rpx;
        box-sizing: border-box;
    }

    .dark_anchor {
        height: 44px;
        margin-top: -44px;
    }

    .tabs {
        display: flex;
        justify-content: start;

        .item {
            margin-right: 20rpx;
        }
    }

    .active {
        color: rgba(214, 142, 68, 1);
    }

    .inventory-table {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 32rpx;
        box-sizing: border-box;
        .inventory-row{
            .specname{
                font-size: 28rpx;
                font-weight: 500;
                color: #333333;
                margin-bottom: 24rpx;

                .name{
                    display: inline-block;
                    background: rgba(243, 243, 243, 1);
                    padding: 4rpx 20rpx;
                    box-sizing: border-box;
                    border-radius: 10rpx;
                    font-size: 24rpx;
                }
            }
            .speccontent{
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 20rpx;
                .spec-name{
                    font-size: 24rpx;
                    color: rgba(0, 0, 0, 0.9);
                }
                .spec-quantity{
                    color: rgba(0, 0, 0, 0.4);
                    font-size: 24rpx;
                }
            }
        }
        .inventory-headers {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 32rpx;
        }

        .table {
            display: inline-block;
            border-collapse: collapse;

            .table-header,
            .table-row {
                display: flex;
                border-bottom: 1rpx solid #f0f0f0;
            }

            .cell,.cell1 {
                padding: 2rpx 8rpx;
                text-align: center;
                min-width: 100rpx;
                box-sizing: border-box;
                &:first-child {
                    text-align: center;
                    min-width: 100rpx;
                }
            }
            .cell2 {
                padding: 2rpx 8rpx;
                text-align: center;
                min-width: 100rpx;
                box-sizing: border-box;
                &:first-child {
                    text-align: center;
                    min-width: 100rpx;
                }
            }

            .header-cell {
                background-color: #fafafa;
            }

            .cell {
                &.color-cell {
                    color: #666666;
                }

                &.unavailable {
                    color: #999999;
                }
            }
        }
    }

    .cell, .cell1 {
        // background: #ffffff;
        // padding: 20rpx 28rpx;
        margin: 20rpx;
        border-radius: 16rpx;
    }

    .detail-cell {
        background: #ffffff;
        padding: 20rpx 28rpx;
        border-radius: 16rpx;
        box-sizing: border-box;
    }

    .tag {
        margin-top: 20rpx;
        font-size: 26rpx;
        color: #999999;
        margin-bottom: 12rpx;
    }

    .jifen {
        font-family: PingFang SC;

        .tags {
            color: rgba(214, 142, 68, 1);
            border: 1rpx solid rgba(214, 142, 68, 1);
            font-size: 24rpx;
            padding: 0 8rpx;
            line-height: 20px;
            font-weight: 400;
            box-sizing: border-box;
        }
    }


    .money {
        color: rgba(193, 122, 50, 1);
    }

    .price {
        font-size: 48rpx;
        font-weight: bold;
    }

    .unit {
        font-size: 28rpx;
    }

    .title {
        margin-top: 20rpx;
        font-weight: bold;
        word-break: break-all;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;

        .type {
            background: rgba(214, 142, 68, 1);
            color: #ffffff;
            font-size: 26rpx;
            padding: 4rpx 12rpx;
            box-sizing: border-box;
            margin-right: 8rpx;
            border-radius: 8rpx;
        }

        .sub-title {
            font-size: 36rpx;
        }
    }

    .cell-option {
        margin-top: 20rpx;
        font-size: 28rpx;

        .option-title {
            display: flex;
            align-items: center;
            margin-right: 20rpx;
            color: #999999;
        }

        .detail {
            display: flex;
            flex: 1;
            justify-content: space-between;
            align-items: baseline;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            .txt {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;

                max-width: 520rpx; // 设置最大宽度
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                display: inline-block;
            }

        }
    }

    .checked {
        display: flex;
        .chevronright {
            width: 16px;
            height: 16px;
        }
    }

    .address {
        display: flex;
        justify-content: space-between;
        white-space: nowrap;
        .chevronright {
            width: 16px;
            height: 16px;
        }
    }

    .service {
        display: flex;
    }

    .service-detail {
        background-color: rgba(250, 53, 52, 0.1);
        color: rgba(214, 142, 68, 1);
        padding: 8rpx 20rpx;
        box-sizing: border-box;
        border-radius: 8rpx;
        display: flex;
        flex: 1;
        justify-content: space-between;
        align-items: baseline;
    }

    .cell-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        &-line {
            background: rgba(214, 142, 68, 1);
            width: 6rpx;
            height: 34rpx;
            margin-right: 8rpx;
        }

        &-title {
            font-weight: bold;
        }

        &-sub-title {
            display: flex;
            align-items: flex-end;
            font-size: 28rpx;
            font-weight: bold;
        }

        &-other {
            display: flex;
            font-size: 24rpx;
        }
    }

    .recommend-cell {
        margin: 0rpx -16rpx;
    }

    .bottom {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 10rpx 24rpx 30rpx;
        box-sizing: border-box;
        // height: 44px;
        line-height: 12px;
        background-color: #ffffff;
        z-index: 999;
        display: flex;
        justify-items: center;
        justify-content: space-around;

        .bottom-option {
            display: flex;
            align-items: center;
        }

        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 4rpx;
            font-size: 24rpx;
            position: relative;
            image {
                width: 44rpx;
                height: 44rpx;
            }
            .bade{
                position: absolute;
                top: -10rpx;
                right: -10rpx;
                z-index: 999;
            }
        }

        .button {
            display: flex;
            align-items: center;
            width: 414rpx;

            .left {
                width: 100%;
                height: 68rpx;
                line-height: 68rpx;
                padding: 0rpx 24rpx;
                box-sizing: border-box;
                background-color: rgba(214, 142, 68, 1);
                color: #ffffff;
                font-size: 28rpx;
                border-radius: 50rpx;
                text-align: center;
            }

            .right {
                margin-left: 24rpx;
                height: 68rpx;
                line-height: 68rpx;
                padding: 0rpx 24rpx;
                box-sizing: border-box;
                background-color: #000000;
                color: #ffffff;
                font-size: 28rpx;
                border-radius: 50rpx;
            }
        }
    }

    .poster-container {
        height: 100vh;

        .save-btn {
            width: 608rpx;
            height: 80rpx;
            line-height: 80rpx;
            background: rgba(214, 142, 68, 1);
            border-radius: 80rpx;
            color: #ffffff;
        }
    }

    @keyframes fadeIn {
        0% {
            opacity: 0;
        }

        100% {
            opacity: 1;
        }
    }
}
</style>
